package com.fly.simple.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.SystemUtils;

public class ShellExecutor
{
    /**
     * execute命令
     * 
     * @param command
     * @throws IOException
     * @see [类、类#方法、类#成员]
     */
    public static List<String> execute(String command)
        throws IOException
    {
        List<String> resultList = new ArrayList<>();
        String[] cmd = SystemUtils.IS_OS_WINDOWS ? new String[] {"cmd", "/c", command} : new String[] {"/bin/sh", "-c", command};
        Process ps = Runtime.getRuntime().exec(cmd);
        try (InputStream in = ps.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(in)))
        {
            String line;
            while ((line = br.readLine()) != null)
            {
                resultList.add(line);
            }
        }
        return resultList;
    }
    
    public static Map<String, Set<String>> getDockerInfo()
        throws IOException
    {
        // ribbon-user-1 8081/tcp
        // ribbon-movie 8082/tcp
        // ribbon-gateway 0.0.0.0:8085->8080/tcp, :::8085->8080/tcp
        String dockerCmd = "docker ps --format \"{{.Names}} {{.Ports}}\"";
        Map<String, Set<String>> map = new TreeMap<>();
        execute(dockerCmd).stream()
            .filter(line -> StringUtils.contains(line, "->"))// 保留带端口映射的应用
            .map(line -> Collections.singletonMap(StringUtils.substringBefore(line, " "),
                Stream.of(StringUtils.substringAfter(line, " ").split(",")).map(p -> StringUtils.substringBetween(p, ":", "->")).filter(StringUtils::isNotBlank).map(p -> p.replace(":", "")).sorted().collect(Collectors.toSet())))
            .forEach(it -> map.putAll(it));
        return map;
    }
}
